﻿
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0
        }

        ul {
            list-style: none
        }

        body {
            background-color: #333;
        }

        .nav {
            width: 800px;
            height: 42px;
            margin: 200px auto;
            background-color: #fff;
            border-radius: 10px;
            position: relative;
        }

        .nav li {
            width: 83px;
            height: 42px;
            text-align: center;
            line-height: 42px;
            float: left;
            cursor: pointer;
        }

        .nav span {
            position: absolute;
            top: 0;
            left: 0;
            width: 83px;
            height: 42px;
            background: url(/static/assets/img/cloud.gif) no-repeat;
        }

        ul {
            position: relative;
        }
    </style>
</head>
<body>
<div class="nav">
    <span id="cloud"></span>
    <ul id="navBar">
        <li>嘻嘻哈哈</li>
        <li>可屯溪区</li>
        <li>神光有的</li>
        <li>了玫琳凯</li>
        <li>快递费奇</li>
        <li>批录取的</li>
        <li>花田喜科</li>
        <li>尤其又不</li>
    </ul>
</div>
<script>
    function my$(id) {
        return document.getElementById(id);
    }
    //匀速动画
    function animate(element, target) {
        //清理定时器
        clearInterval(element.timeId);
        element.timeId = setInterval(function () {
            //获取当前位置
            var current = element.offsetLeft;
            var step = (target - current) / 10;
            //判断怎么移动（向左，还是向右）
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            current += step;
            element.style.left = current + "px";
            if (current == target) {
                clearInterval(element.timeId);
            }
            //测试代码：
            console.log("目标位置：" + target + "当前位置" + current + "每次移动的步数" + step);
        }, 20);
    }


    //获取云彩
    var cloud = my$("cloud");
    // 获取所以的li标签
    var list = my$("navBar").children;
    //循环遍历分别注册鼠标进入，鼠标离开，鼠标点击事件
    for (var i = 0; i < list.length; i++) {
        //鼠标进入
        list[i].onmouseover = mouseoverHandle;
        //点击事件
        list[i].onclick = clickHandle;
        //鼠标离开事件
        list[i].onmouseout = mouseoutHandle;
    }

    function mouseoverHandle() {//进入
        //移动到鼠标进入li的位置
        animate(cloud, this.offsetLeft);
    }
    //点击的时候，记录此次的位置
    //初始为0
    var lastPosition = 0;
    function clickHandle() {//点击
        //记录此刻点击事件的位置
        lastPosition = this.offsetLeft;
    }
    function mouseoutHandle() {
        //离开移动到上次点击的位置，相当于原地移动
        animate(cloud, lastPosition);
    }

</script>
</body>
</html>
